import { useEffect, useRef, useState } from 'react';
// import rawCode from './test.tsx?raw';
import { codeToHtml } from 'shiki';
import { transformerColorizedBrackets } from '@shikijs/colorized-brackets'
import styles from './index.module.scss';
import { useSettingStore } from '@/store';
import SvgIcon from '@/components/SvgIcon/index'

interface CodeBlockProps {
  rawCode: string
  rawType: string
}

const CodeBlock: React.FC<CodeBlockProps> = ({rawCode, rawType}) => {
  const codeRef = useRef<HTMLDivElement>(null);
  const { theme } = useSettingStore()
  const [ expanded, setExpanded ] = useState(true)
  const [ copySuccess, setCopySuccess ] = useState(false)
  const lineCount = rawCode.trim().split('\n').length;
  useEffect(() => {
    (async () => {
      const html = await codeToHtml(rawCode, {
        lang: rawType,
        theme,
        colorReplacements: {
          '#ce92a4': '#c586c0',
          '#af00db': '#7b30d0',
        },
        transformers: [transformerColorizedBrackets()],
      });
      if (codeRef.current) codeRef.current.innerHTML = html;
    })();

  }, [theme]);

  const copyCodeFun = async() => {
    if( copySuccess ){
      return
    }
    try {
      await navigator.clipboard.writeText(rawCode);
    } catch {
      // 降级
      const el = document.createElement('textarea');
      el.value = rawCode;
      document.body.appendChild(el);
      el.select();
      document.execCommand('copy');
      document.body.removeChild(el);
    }
    setCopySuccess(true)
    setTimeout(() => {
      setCopySuccess(false)
    }, 1000);
  }
  return (
    <>
      {/* <button onClick={() => setTheme(theme === 'dark-plus' ? 'light-plus' : 'dark-plus')}>
        切换 {theme === 'dark-plus' ? '亮' : '暗'} 色
      </button> */}
      <div className={styles.con}>
        <div className={styles.title}>
          <div className={styles.type}>{rawType}</div>
          <div className={styles.btn}
            onClick={() => setExpanded(!expanded)}>
              <SvgIcon name={ expanded ? 'collapse' : 'unfold'} size={14}/>
              { expanded ? '收起' : '展开'}
          </div>
          <div className={`${styles.btn} ${ copySuccess ? styles.copySuccessCss : '' }`}
            onClick={() => copyCodeFun()}>
            <SvgIcon name={ copySuccess ? 'tick' : 'copy'} size={14}/>
            { copySuccess ? '已复制' : '复制'}
          </div>
        </div>
        <div ref={codeRef} className={ expanded ? '' : 'hidden'}/> 
        <div className={`${styles.hid} ${expanded ? 'hidden' : ''}`}>已隐藏{lineCount}行</div>
      </div>
    </>
  );
};

export default CodeBlock;